import { Form, Input,Button,Popup } from 'antd-mobile'
import { login } from '../../api';
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { saveUserId } from '../../store/userSlice';
import './login.scss'

function Login() {
  let [visible2,setVisible2] = useState(false)
  let [message,setMessage] = useState('')
  let navigate = useNavigate()
  let dispatch= useDispatch()
  const submit = ({loginname,password})=>{
    
    login({loginname,password}).then((res)=>{ // 调用登录请求进行登录
      console.log(res);
      if(res.data.code === '200'){
        localStorage.setItem('token',res.data.data.token)  // 记录token
        // 向仓库里记录用户id
        console.log(res.data.data)
        dispatch(saveUserId(res.data.data.userid))
        // 显示弹出消息
        setVisible2(true)
        setMessage(res.data.data.message)
        setTimeout(()=>{
          setVisible2(false) // 关闭弹框
          navigate("/home")
        },1000)
       
      }
    })
  }
  return (
    <div className="App">
      <Popup
        
          visible={visible2}
          mask={false}
          onMaskClick={() => {
            setVisible2(false)
          }}
          position='top'
          bodyStyle={{ height: '10vh' }}
        >
          {message}
        </Popup>

       <Form layout='horizontal'  onFinish={submit}>
        <Form.Item label='用户名' name='loginname'> 
          <Input placeholder='请输入' />
        </Form.Item>
        <Form.Item label='密码' name='password'>
          <Input placeholder='请输入'  />
        </Form.Item>
        <Form.Item>
          <Button block type='submit' color='primary' size='large'>登录</Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
